<template>
  <div class="app-container">
    <el-form ref="queryForm" :inline="true" :model="queryForm">
      <el-form-item label="用户真实名称" prop="userRealName">
        <el-input
          v-model="queryForm.userRealName"
          size="small"
          placeholder="请输入用户真实名称"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <!-- <el-form-item label="卖家真实名称" prop="saleUserName">
        <el-input
          v-model="queryForm.saleUserName"
          size="small"
          placeholder="请输入卖家真实名称"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item> -->
      <el-form-item label="买家id" prop="buyUserId">
        <el-input
          v-model="queryForm.buyUserId"
          size="small"
          placeholder="请输入买家id"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <!-- <el-form-item label="卖家id" prop="saleUserId">
        <el-input
          v-model="queryForm.saleUserId"
          size="small"
          placeholder="请输入卖家id"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item> -->
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          :loading="loadingSearch"
          size="mini"
          @click="handleQuery"
        >搜索</el-button>
        <el-button
          type="primary"
          icon="el-icon-download"
          :loading="loadingDown"
          size="mini"
          @click="handleDownLoad"
        >下载</el-button>
        <el-button
          type="primary"
          icon="el-icon-download"
          :loading="loadingDown"
          size="mini"
          @click="handleDownLoadRecommend"
        >推荐收益下载</el-button>
        <el-button
          icon="el-icon-refresh"
          size="mini"
          @click="resetQuery"
        >重置</el-button>
      </el-form-item>
      <el-form-item>
        <span style="margin-left: 20px;">昨日上架总金额：</span>
        <span style="color: red;margin-left: 10px;">￥{{ totalSale.toFixed(2) }}</span>
        <span style="margin-left: 20px;">今日买单总金额：</span>
        <span style="color: red;margin-left: 10px;">￥{{ totalBuy.toFixed(2) }}</span>
        <span style="margin-left: 20px;">今日推荐收益总金额：</span>
        <span style="color: red;margin-left: 10px;">￥{{ totalRecommend.toFixed(2) }}</span>
        <!-- <span style="margin-left: 20px;">总计垫付金额：</span>
        <span style="color: red;margin-left: 10px;">￥{{ totalIncome>0 ? totalIncome.toFixed(2): '0.00' }}</span> -->
      </el-form-item>
    </el-form>

    <el-table
      v-loading="loading"
      border
      :data="orderList"
      style="width: 100%"
      @sort-change="handleSortChange"
    >
      <el-table-column
        align="center"
        min-width="100"
        label="用户ID"
        prop="id"
        width="100"
      />
      <el-table-column
        align="center"
        width="150"
        label="用户姓名"
        prop="userRealName"
        sortable="custom"
      />
      <!-- <el-table-column align="center" label="身份证号" prop="peopleNum" min-width="100" /> -->
      <el-table-column align="center" label="手机号" prop="mobile"  />
      <el-table-column align="center" label="直推人" prop="invitePeopleName" />

      <el-table-column align="center" label="昨日买单总额" prop="yesterBuyMoney"  />

      <el-table-column align="center" label="昨日上架金额" prop="selloutMoney"  />
      <el-table-column align="center" label="今日购物车金额" prop="buymoney"  />
      <!--<el-table-column align="center" label="是否需垫付" prop="goodsCount" width="100" />-->
      <el-table-column align="center" label="买单金额差" prop="buyMoneyDifference"  />
      <el-table-column align="center" label="差额" prop="paymentDifference" />

    </el-table>

    <pagination
      v-show="total"
      :total="total"
      :page.sync="queryForm.pageNum"
      :limit.sync="queryForm.pageSize"
      @pagination="getList"
    />
  </div>
</template>
<script>
import {
  delOrder,
  getOrder,
  refundOrder,
  getTodayData,
  listChannel,
  clickShip, splitOrderReq, listUser, updateSaleStatus, downloadToday, downloadRecommend, todayRecommendedIncomeCount
} from '@/api/shop/order'
import { yuan } from '@/utils'
import {excelNameDate} from  '@/utils/index'


export default {
  name: 'PurchaseOrderList',
  filters: {
    yuan
  },
  data() {
    return {
      loading: true,
      loadingSearch:false,
      // 列表总数
      total: 0,
      // 日期范围
      dateRange: [],
      totalBuy: 10000,
      totalSale: 11000,
      totalIncome: 0,
      // 订单状态数据字典
      orderStatusOptions: [],
      payTypeOptions: [
        { name: '微信', value: '1' },
        { name: '支付宝', value: '2' },
        { name: '测试', value: '3' }
      ],
      // 查询参数
      queryForm: {
        pageNum: 1,
        pageSize: 10,
        orderSn: undefined,
        userId: undefined,
        name: undefined,
        buyUserId:undefined

      },
      // 角色列表
      orderList: [],
      orderDialogVisible: false,
      orderDetail: {
        order: {},
        user: {},
        orderGoods: []
      },
      totalRecommend:0,
      channels: [],
      shipForm: {
        orderId: undefined,
        shipChannel: undefined,
        shipSn: undefined
      },
      shipFormRules: {
        shipChannel: [
          { required: true, message: '发货渠道不能为空', trigger: 'blur' }
        ],
        shipSn: [
          { required: true, message: '发货编号不能为空', trigger: 'blur' }
        ]
      },
      shipDialogVisible: false,
      showOrderVisible: false,
      formModel: {
        tableData: []
      },
      options: [],
      loadingDown: false
    }
  },
  created() {
    this.getOptions()
    this.getList()
    this.getRecommend()
    this.getChannel()
  },
  methods: {
    async getRecommend(){
      const res =await todayRecommendedIncomeCount()
      this.totalRecommend = res.map.incomeCount
    },
    // 获取买家
    async getOptions() {
      const {
        map: { userList }
      } = await listUser()
      this.options = userList
    },
    async onConfirm() {
      this.$refs.formRef.validate(async valid => {
        if (!valid) {
          return
        }
        await splitOrderReq({ ...this.formModel })
        this.$message.success('操作成功')
        this.formModel = {}
        this.$refs.formRef.resetFields()
        this.getList()
        this.showOrderVisible = false
      })
    },
    handleOrder(record) {
      this.formModel.orderId = record.id
      this.showOrderVisible = true
    },
    handleStatus(record) {
      updateSaleStatus({ 'orderId': record.id }).then(res => {
        if (res.code === 200) {
          this.$message.success('操作成功')
        } else {
          this.$message.error('操作失败')
        }
        this.getList()
      })
    },
    getChannel() {
      listChannel().then((response) => {
        this.channels = response.map.data
      })
    },
    handleQuery() {
      if(this.loadingSearch){
        this.timer = setTimeout(()=>{
          this.loadingSearch =false
          clearTimeout(this.timer)
        },3000)
        return false
      }
      this.loadingSearch =true
      this.orderList = []
      this.getList()
    },
    /**
       * 表单重置
       */
    resetQuery() {
      this.$refs.queryForm.resetFields()
      this.dateRange = []
      this.handleQuery()
    },
    async getList() {
      const {
        map: {
          page: { records: data, total },
          buymoneyCount,
          incomeCount,
          selloutMoneyCount
        }
      } = await getTodayData({ ...this.queryForm, timeStr: this.dateRange && this.dateRange.length ? `${this.dateRange[0]},${this.dateRange[1]}` : '' })
      this.total = total
      this.totalBuy = buymoneyCount
      this.totalSale = selloutMoneyCount
      this.totalIncome = incomeCount
      data.forEach(item => {
        if (item.buymoney == null) {
          item.buymoney = 0
        }
        if (item.selloutMoney == null) {
          item.selloutMoney = 0
        }
        if (item.income == null || item.income < 0) {
          item.income = 0
        }
      })
      this.orderList = data
      console.log(this.orderList)
      this.loading = false
      this.timer = setTimeout(()=>{
          this.loadingSearch =false
          clearTimeout(this.timer)
      },3000)
    },
    /**
       * 后端排序
       */
    handleSortChange(sort) {
      this.queryForm.sortName = sort.prop
      this.queryForm.sortOrder = sort.order
      console.log(sort)
      this.getList()
    },
    async handleDetail(row) {
      const {
        map: { data }
      } = await getOrder(row.id)
      this.orderDetail = data
      this.orderDialogVisible = true
    },
    handleShip(row) {
      this.shipForm = {
        orderId: row.id,
        shipChannel: undefined,
        shipSn: undefined
      }
      this.shipDialogVisible = true
    },
    clickShip(row) {
      this.$refs['shipForm'].validate(async(valid) => {
        if (valid) {
          const { code, msg } = await clickShip(this.shipForm)
          if (code === 200) {
            this.$message.success('发货成功')
            this.shipDialogVisible = false
            this.getList()
          } else {
            this.$message.error(msg)
          }
        }
      })
    },
    handleRefund(row) {
      this.$confirm(
        '是否确认为订单编号为 [' + row.orderSn + '] 的订单退款?',
        '警告',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      )
        .then(function() {
          return refundOrder(row.id)
        })
        .then(() => {
          this.getList()
          this.$message.success('退款成功')
        })
        .catch(function(e) {})
    },
    /**
       * 删除按钮
       */
    async handleDelete(row) {
      const orderId = row.id
      this.$confirm(
        '是否确认删除订单编号为 [' + row.orderSn + '] 的订单吗?',
        '警告',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      )
        .then(function() {
          return delOrder(orderId)
        })
        .then(() => {
          this.getList()
          this.$message.success('删除成功')
        })
        .catch(function(e) {})
    },
    handleDownLoadRecommend(){
      this.$confirm(
        '是否下载推荐收益数据',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'info'
        }
      )
        .then(res => {
          downloadRecommend().then(res => {
            const blob = new Blob([res.data], { type: 'application/msword' })// new Blob([res])中不加data就会返回下图中[objece objece]内容（少取一层）
            console.log(blob)
            const dates = excelNameDate()
            // const fileName = `${month}-${day} ${h}:${m}:${s}调单数据.xls`// 下载文件名称
            const fileName = `${dates}推荐收益数据.xls`// 下载文件名称
            const elink = document.createElement('a')
            elink.download = fileName
            elink.style.display = 'none'
            elink.href = URL.createObjectURL(blob)
            document.body.appendChild(elink)
            elink.click()
            URL.revokeObjectURL(elink.href) // 释放URL 对象
          })
          // this.loadingDown = true
          console.log(res)
        })
    },
    handleDownLoad() {
      this.$confirm(
        '是否下载今日数据',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'info'
        }
      )
        .then(res => {
          downloadToday().then(res => {
            const blob = new Blob([res.data], { type: 'application/msword' })// new Blob([res])中不加data就会返回下图中[objece objece]内容（少取一层）
            console.log(blob)
            const dates = excelNameDate()
            // const fileName = `${month}-${day} ${h}:${m}:${s}调单数据.xls`// 下载文件名称
            const fileName = `今日数据${dates}.xls`// 下载文件名称
            const elink = document.createElement('a')
            elink.download = fileName
            elink.style.display = 'none'
            elink.href = URL.createObjectURL(blob)
            document.body.appendChild(elink)
            elink.click()
            URL.revokeObjectURL(elink.href) // 释放URL 对象
          })
          // this.loadingDown = true
          console.log(res)
        })
    }
  }
}
</script>
  <style lang="scss" scoped>
  .more_btn{
    margin-left: 10px;
  }
  </style>
